/**
 * Created by tanbingqin on 2018/10/12.
 */
import React from 'react';
import { connect } from 'react-redux';
import { messages } from 'share/common';
import { Form, Spin, Input, Tabs, Row, Col, DatePicker, Affix, Button, Divider, Icon, message, Select, InputNumber, TimePicker, Modal } from 'antd';
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const Option = Select.Option;
import moment from 'moment';
import errorMessage from 'share/errorMessage';
import travelService from 'containers/request/travel-request/travel.service'
import travelUtil from 'containers/request/travel-request/travelUtil'
import TravelLocation from 'containers/request/travel-request/comp/location'
import TravelPrompt from 'containers/request/travel-request/travel-prompt'

class TravelDiDi extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      nowTab: 'travel',
      isLoading: false,
      editData: null, //编辑状态下的行程数据
      baseStartDate: null,
      baseEndDate: null,
      startDate: null, //按日期用车的开始日期
      endDate: null, //按日期用车的结束日期
      didiRules: [], //滴滴用车制度
      selectRuleName: '',
      selectRule: null,
      itineraryDetailList: [
        {
          cityName: '',
          cityCode: '',
          showValue: '',
          citySearchList: [],
          date: null
        },
        {
          cityName: '',
          cityCode: '',
          showValue: '',
          citySearchList: [],
          date: null
        },
        {
          cityName: '',
          cityCode: '',
          showValue: '',
          citySearchList: [],
          date: null
        }
      ], //行程详情，从某地到某地到某地
      selectCities: [], //日期用车选中的城市，马上用车、接送机用车中选中的城市
      useCarAmount: null, //用车金额
      useCarNum: 1, //用车次数
      instantCarAmount: null, //马上用车中的用车金额
      instantCarNum: 1, //马上用车中的用车次数
      pickupPlanList: [
        {
          plan: '',
          startDate: null,
          endDate: null
        }
      ], //接送机用车
      typeList: [], //接送机类型列表
      didiProperties: {}, //滴滴行程的配置  这个里面是哪些tabs开启的配置
      didiFieldProperties: {}, //滴滴行程字段的配置 是否显示 是否必填
      standardEnable: false, //是否走差旅标准
      promptList: [] //行程提示语的配置
    };
  };

  componentWillMount() {
    //这里在进单据详情页时就渲染了，此时并不一定能拿到行程数据，不能在这做数据初始化
    let tempMap = this.props.params['travelInfo']['customFormPropertyMap'];
    this.setState({
      standardEnable: tempMap['ca.travel.applypolicy.enable'] === 'true',
      promptList: tempMap['travel.itinerary.tips'] ? JSON.parse(tempMap['travel.itinerary.tips']) : []
    });
    if (tempMap['didi.itinerary.enable'] === "true" && tempMap['didi.itinerary.enable.types'] && tempMap['application.property.control.fields.car']) {
      this.setState({
        didiProperties: JSON.parse(tempMap['didi.itinerary.enable.types']),
        didiFieldProperties: JSON.parse(tempMap['application.property.control.fields.car'])
      }, () => {
        this.setDiDiRules();
        this.initTypeList();
      });
    }
  };

  componentWillReceiveProps(nextProps) {
    let { itineraryDetailList, editData, pickupPlanList, startDate, endDate } = this.state;
    //处理打开侧滑
    if (!this.props.isShowDiDiSlide && nextProps.isShowDiDiSlide) {
      let baseStartDate = travelUtil.getFormHeadValue(nextProps.params.defaultValue, 'start_date');
      this.setState({baseStartDate: moment(baseStartDate)});
      let baseEndDate = travelUtil.getFormHeadValue(nextProps.params.defaultValue, 'end_date');
      this.setState({baseEndDate: moment(baseEndDate)});
      if (nextProps.params.editDidi) {
        //编辑用车行程
        this.setState({editData: nextProps.params.editDidi}, this.initEditData);
      } else {
        //新建用车行程
        this.initNowTab();
        if (baseStartDate) {
          itineraryDetailList[0].date = moment(baseStartDate);
          pickupPlanList[0].startDate = moment(baseStartDate);
          startDate = moment(baseStartDate);
        }
        if (baseEndDate) {
          itineraryDetailList[itineraryDetailList.length - 1].date = moment(baseEndDate);
          pickupPlanList[0].endDate = moment(baseEndDate);
          endDate = moment(baseEndDate);
        }
        this.setState({itineraryDetailList, pickupPlanList, startDate, endDate});
      }
    }

    //处理关闭侧滑
    if (this.props.isShowDiDiSlide && !nextProps.isShowDiDiSlide) {
      this.resetValue();
    }
  };

  setDiDiRules = () => {
    travelService.getDiDiRegulation(this.props.applicant.userOID).then(res => {
      this.setState({didiRules: res.data});
    });
  };

  //默认选中第一个规则
  initDidiRule = () => {
    const { nowTab, didiRules } = this.state;
    if (nowTab === 'travel' && didiRules['businessRegulationList'] && didiRules['businessRegulationList'].length) {
      this.setState({selectRule: didiRules['businessRegulationList'][0], selectRuleName: didiRules['businessRegulationList'][0].regulationName}, this.checkRule);
    }
    if (nowTab === 'date' && didiRules['dateRegulationList'] && didiRules['dateRegulationList'].length) {
      this.setState({selectRule: didiRules['dateRegulationList'][0], selectRuleName: didiRules['dateRegulationList'][0].regulationName}, this.checkRule);
    }
    if (nowTab === 'count' && didiRules['numberRegulationList'] && didiRules['numberRegulationList'].length) {
      this.setState({selectRule: didiRules['numberRegulationList'][0], selectRuleName: didiRules['numberRegulationList'][0].regulationName}, this.checkRule);
    }
  };

  //校验用车制度的权限，新建带出默认值，切换tab带出默认值，切换制度时都要进行用车制度权限校验
  checkRule = () => {
    const { oid } = this.props.params;
    const { selectRule } = this.state;
    if (oid && selectRule.regulationId) {
      this.setState({isLoading: true});
      travelService.checkDiDiRegulation(oid, selectRule.regulationId).then(res => {
        if (res.data && res.data.success) {
          let userNameCheckList = []; //权限有问题的user的name的list
          let userNameStr = '';
          res.data.rows && res.data.rows.userCheckResult.map(user => {
            if (!user.result) {
              userNameCheckList.push(user.userName);
            }
          });
          userNameStr = userNameCheckList.join(',');
          let content = messages('request.key642',{arg1: userNameCheckList.length,arg2: selectRule.regulationName,arg3: userNameStr})/*{arg1}人未分配“{arg2}”：{arg3}*/;
          if (userNameStr) {
            Modal.info({
              title: messages('request.key563')/*注意*/,
              content: <div>
                <p>{messages('request.key643')/*当前出行人中*/}：</p>
                <p>{content}</p>
                <p>{messages('request.key644')/*审批通过后将没有用车权限。*/}</p>
              </div>,
              okText: messages('common.ok'),
              onOk: () => {}
            });
          }
        } else {
          message.error(res.data.message);
        }
      }).finally(() => {
        this.setState({isLoading: false});
      });
    }
  };

  //重置表单
  resetValue = () => {
    this.setState({
      editData: null
    });
    this.setDiDiRules();
    this.initTypeList();
    this.resetTravel();
    this.resetDate();
    this.resetCount();
    this.resetInstant();
    this.resetPickup();
  };

  //初始化接送机类型
  initTypeList = () => {
    travelService.getTypeList().then(res => {
      this.setState({typeList: res.data});
    });
  };

  //根据配置，默认展示第一个启用的tab
  initNowTab = () => {
    const { didiProperties } = this.state;
    if (didiProperties.TRAVEL) {
      this.setState({nowTab: 'travel'}, this.initDidiRule);
    } else if (didiProperties.BUSINESS_TRIP_BY_DATE) {
      this.setState({nowTab:'date'}, this.initDidiRule);
    } else if (didiProperties.BUSINESS_TRIP_BY_TIMES) {
      this.setState({nowTab: 'count'}, this.initDidiRule);
    } else if (didiProperties.CARQUICK) {
      this.setState({nowTab: 'instant'});
    } else if (didiProperties.CARPICKUP) {
      this.setState({nowTab: 'pickup'});
    }
  };

  //Tabs点击
  onChangeTabs = (key) => {
    if (key === 'travel') {
      this.resetTravel();
    }
    if (key === 'date') {
      this.resetDate();
    }
    if (key === 'count') {
      this.resetCount();
    }
    if (key === 'instant') {
      this.resetInstant();
    }
    if (key === 'pickup') {
      this.resetPickup();
    }
    this.setState({
      selectRule: null,
      selectRuleName: '',
      nowTab : key
    }, this.initDidiRule);
  };

  //重置差旅用车数据
  resetTravel = () => {
    const { baseStartDate, baseEndDate } = this.state;
    let itineraryDetailList = [
      {
        cityName: '',
        cityCode: '',
        showValue: '',
        citySearchList: [],
        date: baseStartDate
      },
      {
        cityName: '',
        cityCode: '',
        showValue: '',
        citySearchList: [],
        date: null
      },
      {
        cityName: '',
        cityCode: '',
        showValue: '',
        citySearchList: [],
        date: baseEndDate
      }
    ];
    this.setState({itineraryDetailList});
    this.props.form.resetFields();
  };

  //初始化编辑状态的行程
  initEditData = () => {
    const { editData } = this.state;
    let selectRule = {};
    //行程列表的接口上没有regulation对象，要根据itineraryOID查详情才有regulation对象
    //selectRule = editData.regulation;
    let selectRuleName = editData.regulationName;
    this.setState({selectRuleName});
    this.setState({isLoading: true});
    travelService.getDiDiItinerary(editData.itineraryOID).then(res => {
      this.setState({isLoading: false});
      selectRule = res.data.regulation;
      this.setState({selectRule});
    }).catch(() => {
      this.setState({isLoading: false});
    });
    this.props.form.setFieldsValue({remark: editData.remark});
    let trips = [];
    if (editData.trips) {
      trips = JSON.parse(editData.trips);
    }
    //差旅用车
    if (editData.approvalType === 1) {
      let itineraryDetailList = [];
      //装载第一个
      itineraryDetailList.push({
        cityName: editData.departureCity,
        cityCode: editData.departureCityCode,
        showValue: editData.departureCity,
        citySearchList: [],
        date: moment(editData.startDate)
      });
      trips.map(trip => {
        let subItinerary = {
          cityName: trip.destinationCity,
          cityCode: trip.destinationCityId,
          showValue: trip.destinationCity,
          citySearchList: [],
          date: moment(trip.endDate)
        };
        itineraryDetailList.push(subItinerary);
      });
      //装载最后一个
      itineraryDetailList.push({
        cityName: editData.destinationCity,
        cityCode: editData.destinationCityCode,
        showValue: editData.destinationCity,
        citySearchList: [],
        date: moment(editData.endDate)
      });
      this.setState({itineraryDetailList, nowTab: 'travel'});
    }
    //按日期用车
    if (editData.approvalType === 3) {
      let selectCities = [];
      trips.map(trip => {
        if (trip.destinationCity && trip.destinationCityId) {
          selectCities.push({label: trip.destinationCity, key: trip.destinationCityId});
        }
      });
      this.setState({
        selectCities,
        nowTab: 'date',
        useCarAmount: editData.tripAmount,
        startDate: moment(editData.startDate),
        endDate: moment(editData.endDate)
      });
    }
    //按次数用车
    if (editData.approvalType === 2) {
      this.setState({nowTab: 'count', useCarNum: editData.tripTimes}, () => {
        //nowTab渲染完成，才可以setFieldsValue，不然field都没有注册完成
        this.props.form.setFieldsValue({
          tripSDate: moment(editData.startDate),
          tripSTime: moment(moment(editData.startDate).format('HH:mm'), 'HH:mm'),
          tripEDate: moment(editData.endDate),
          tripETime: moment(moment(editData.endDate).format('HH:mm'), 'HH:mm')
        });
      });
    }
    //马上用车
    if (editData.approvalType === 4) {
      let selectCities = [];
      editData.travelCarItineraryTrips && editData.travelCarItineraryTrips.map(trip => {
        if (trip.departureCity && trip.departureCityId) {
          selectCities.push({label: trip.departureCity, key: trip.departureCityId});
        }
      });
      this.setState({selectCities, nowTab: 'instant', instantCarNum: editData.tripTimes, instantCarAmount: editData.tripAmount}, () => {
        //nowTab渲染完成，才可以setFieldsValue，不然field都没有注册完成
        this.props.form.setFieldsValue({
          instantSDate: editData.startDate ? moment(editData.startDate) : null,
          instantEDate: editData.endDate ? moment(editData.endDate) : null
        });
      });
    }
    //接送机用车
    if (editData.approvalType === 5) {
      let selectCities = [];
      editData.travelCarItineraryTrips && editData.travelCarItineraryTrips.map(trip => {
        if (trip.departureCity && trip.departureCityId) {
          selectCities.push({label: trip.departureCity, key: trip.departureCityId});
        }
      });
      let pickupPlanList = [];
      let planItem = {};
      planItem.plan = editData.carPickUpType;
      planItem.startDate = editData.startDate ? moment(editData.startDate) : null;
      planItem.endDate = editData.endDate ? moment(editData.endDate) : null;
      pickupPlanList.push(planItem);
      this.setState({selectCities, pickupPlanList, nowTab: 'pickup'});
    }
  };

  //重置按日期用车数据
  resetDate = () => {
    const { baseStartDate, baseEndDate } = this.state;
    this.setState({
      selectCities: [],
      useCarAmount: null,
      startDate: baseStartDate ? baseStartDate : null,
      endDate: baseEndDate ? baseEndDate : null
    });
    this.props.form.resetFields();
  };

  //重置按次用车数据
  resetCount = () => {
    this.setState({
      useCarNum: 1
    });
    this.props.form.resetFields();
  };

  //重置马上用车数据
  resetInstant = () => {
    this.setState({
      selectCities: [],
      instantCarNum: 1,
      instantCarAmount: null
    });
    this.props.form.resetFields();
  };

  //重置接送机／火车数据
  resetPickup = () => {
    const { baseStartDate, baseEndDate } = this.state;
    this.setState({
      selectCities: [],
      pickupPlanList: [
        {
          plan: '',
          startDate: baseStartDate ? baseStartDate : null,
          endDate: baseEndDate ? baseEndDate : null
        }
      ]
    });
  };

  renderTabs = () => {
    const { isLoading, didiProperties } = this.state;
    let tabs = [];
    didiProperties.TRAVEL && tabs.push({key: 'travel', name: messages('request.key478')/*差旅用车*/});
    didiProperties.BUSINESS_TRIP_BY_DATE && tabs.push({key: 'date', name: messages('request.key480')/*按日期用车*/});
    didiProperties.BUSINESS_TRIP_BY_TIMES && tabs.push({key: 'count', name: messages('request.key492')/*按次用车*/});
    didiProperties.CARQUICK && tabs.push({key: 'instant', name: messages('request.key588')/*马上用车*/});
    didiProperties.CARPICKUP && tabs.push({key: 'pickup', name: messages('request.key589')/*接送机／火车*/});
    return (
      tabs.map(tab => {
        return <TabPane tab={tab.name} key={tab.key} disabled={isLoading || tab.disabled}/>
      })
    )
  };

  //渲染label，index为itineraryDetailList中的序号，type为'city'或者'date'
  renderLabel = (index, type) => {
    if (type === 'city') {
      if (index === 0) {
        return messages('request.key376')/*出发城市*/;
      } else if (index === this.state.itineraryDetailList.length - 1) {
        return messages('request.key493')/*返回城市*/;
      } else {
        return messages('request.key494',{arg1:index})/*目的城市{arg1}*/;
      }
    }
    if (type === 'date') {
      if (index === 0) {
        return messages('request.key379')/*出发日期*/;
      } else if (index === this.state.itineraryDetailList.length - 1) {
        return messages('request.key380')/*返回日期*/;
      } else {
        return messages('request.key495')/*离开日期*/;
      }
    }
    return '';
  };

  //添加一个目的城市行程
  addSubItinerary = () => {
    const { itineraryDetailList } = this.state;
    //校验之前的目的城市是否都必填了
    let i = 1;
    for (i; i < itineraryDetailList.length - 1; i++) {
      if (!itineraryDetailList[i].cityCode) {
        message.error(messages('request.key496',{arg1:i})/*请填写目的城市{arg1}的城市*/);
        return;
      }
      if (!itineraryDetailList[i].date) {
        message.error(messages('request.key497',{arg1:i})/*请填写目的城市{arg1}的日期*/);
        return;
      }
    }
    if (itineraryDetailList.length >= 32) {
      message.error(messages('request.key498')/*最多添加30个目的城市*/);
      return;
    }
    let subItinerary = {
      cityName: '',
      cityCode: '',
      showValue: '',
      citySearchList: [],
      date: null
    };
    itineraryDetailList.splice(itineraryDetailList.length - 1, 0, subItinerary);
    this.setState({itineraryDetailList});
  };

  //移除一个目的城市行程
  removeSubItinerary = (index) => {
    const { itineraryDetailList } = this.state;
    itineraryDetailList.splice(index, 1);
    this.setState({itineraryDetailList: itineraryDetailList});
  };

  //差旅用车中选择日期
  onChangeDate = (value, index) => {
    const { itineraryDetailList } = this.state;
    itineraryDetailList[index].date = value;
    this.setState({itineraryDetailList});
  };

  //接送用车中选择日期
  onChangePickupDate = (value, index, key) => {
    const { pickupPlanList } = this.state;
    pickupPlanList[index][key] = value;
    this.setState({pickupPlanList});
  };

  handleChangeDate = (value, key) => {
    this.setState({[key]: value});
  };

  disabledDate = (current) => {
    const { baseStartDate, baseEndDate, nowTab, selectRule } = this.state;
    return !(moment(current).isSame(baseStartDate, 'day')
    || moment(current).isSame(baseEndDate, 'day')
    || moment(current).isBetween(baseStartDate, baseEndDate, 'day'));
  };

  //差旅用车-选择城市
  selectCity = (cityObj, index) => {
    const { itineraryDetailList } = this.state;
    itineraryDetailList[index].showValue = cityObj.vendorAlias;
    itineraryDetailList[index].cityName = cityObj.vendorAlias;
    itineraryDetailList[index].cityCode = cityObj.code;
    //改变出发城市，同时修改返回城市
    if (index === 0) {
      itineraryDetailList[itineraryDetailList.length - 1].showValue = cityObj.vendorAlias;
      itineraryDetailList[itineraryDetailList.length - 1].cityName = cityObj.vendorAlias;
      itineraryDetailList[itineraryDetailList.length - 1].cityCode = cityObj.code;
      itineraryDetailList[itineraryDetailList.length - 1].citySearchList = [];
    }
    this.setState({itineraryDetailList});
  };

  //接送机用车-选择类型
  handleSelectType = (value, index) => {
    const { pickupPlanList } = this.state;
    pickupPlanList[index].plan = value ? value : '';
    this.setState({pickupPlanList});
  };

  //选择规则
  selectRule = (e, opt) => {
    this.setState({selectRule: opt.props['data-rule'], selectRuleName: opt.props['data-rule'].regulationName}, this.checkRule);
  };

  //日期用车 原多选城市改成单选控件
  handleSelectSingleCity = (cityObj) => {
    this.setState({
      selectCities: (cityObj && cityObj.adCode) ? [
        {
          label: cityObj.adName,
          key: cityObj.adCode
        }
      ] : []
    });
  };

  //用车次数修改
  handleChangeCarNum = (num, key) => {
    if (num !== null && num !== undefined && num > 99) {
      num = 99;
    }
    this.setState({[key]: num});
  };

  //用车金额修改
  handleChangeCarAmount = (num, key) => {
    this.setState({[key]: num});
  };

  //关闭侧滑
  closeDiDiSlide = () => {
    this.props.close();
  };

  //是否校验通过
  validateData = (values) => {
    const { nowTab, itineraryDetailList, selectRule, selectCities, useCarAmount, useCarNum, startDate, endDate,
      instantCarAmount, instantCarNum, pickupPlanList, didiFieldProperties, standardEnable
    } = this.state;
    //用车规则都是必填的
    if (!selectRule && ['travel', 'date', 'count'].indexOf(nowTab) > -1) {
      message.error(messages('request.key500')/*请选择用车制度*/);
      return false;
    }
    if (nowTab === 'travel') {
      let errMsg = '';
      itineraryDetailList.map(itinerary => {
        if (!itinerary.cityName || !itinerary.cityCode || !itinerary.date) {
          errMsg = messages('request.key501')/*请填写完整行程详情*/;
        }
      });
      if (errMsg) {
        message.error(errMsg);
        return false;
      } else {
        //在非空的基础上校验日期是否是升序
        let i = 0;
        for (i; i < itineraryDetailList.length - 1; i++) {
          if (moment(itineraryDetailList[i].date).isAfter(itineraryDetailList[i + 1].date, 'day')) {
            message.error(messages('request.key502')/*请按日期升序填写*/);
            return false;
          }
        }
      }
    }
    if (nowTab === 'date') {
      if (!startDate) {
        message.error(messages('request.key503')/*请输入开始日期*/);
        return false;
      }
      if (!endDate) {
        message.error(messages('request.key504')/*请输入结束日期*/);
        return false;
      }
      if (selectCities.length === 0 && didiFieldProperties.businessTripByDate.departureCity.show && didiFieldProperties.businessTripByDate.departureCity.required) {
        message.error(messages('request.key505')/*请选择用车城市*/);
        return false;
      }
      if (moment(startDate).isAfter(endDate, 'day')) {
        message.error(messages('request.key506')/*结束日期不能早于开始日期*/);
        return false;
      }
      if (selectRule && selectRule.useDate === '限制周六日用车') {
        if (moment(startDate).format('E') === '6' || moment(startDate).format('E') === '7') {
          message.error(messages('request.key611')/*开始日期不可以为周末*/);
          return false;
        }
        if (moment(endDate).format('E') === '6' || moment(endDate).format('E') === '7') {
          message.error(messages('request.key612')/*结束日期不可以为周末*/);
          return false;
        }
      }
      if ((useCarAmount === null || useCarAmount === undefined) && !standardEnable
        && didiFieldProperties.businessTripByDate.carStandard.show
        && didiFieldProperties.businessTripByDate.carStandard.required) {
        message.error(messages('request.key507')/*请输入用车金额*/);
        return false;
      }
    }
    if (nowTab === 'count') {
      if (useCarNum === null || useCarNum === undefined) {
        message.error(messages('request.key508')/*请输入用车次数*/);
        return false;
      }
      let startDateStr = moment(values['tripSDate']).format('YYYY-MM-DD') + ' ' + moment(values['tripSTime']).format('HH:mm');
      let endDateStr = moment(values['tripEDate']).format('YYYY-MM-DD') + ' ' + moment(values['tripETime']).format('HH:mm');
      if (moment(startDateStr).isAfter(endDateStr, 'minute')) {
        message.error(messages('request.key506')/*结束日期不能早于开始日期*/);
        return false;
      }
    }
    if (nowTab === 'instant') {
      if (!values['instantSDate']) {
        message.error(messages('request.key503')/*请输入开始日期*/);
        return false;
      }
      if (!values['instantEDate']) {
        message.error(messages('request.key504')/*请输入结束日期*/);
        return false;
      }
      if (moment(values['instantSDate']).isAfter(values['instantEDate'], 'day')) {
        message.error(messages('request.key506')/*结束日期不能早于开始日期*/);
        return false;
      }
      if (selectCities.length === 0 && didiFieldProperties.carQuick.departureCity.show && didiFieldProperties.carQuick.departureCity.required) {
        message.error(messages('request.key505')/*请选择用车城市*/);
        return false;
      }
      if ((instantCarNum === null || instantCarNum === undefined)
        && didiFieldProperties.carQuick.useTimes.show
        && didiFieldProperties.carQuick.useTimes.required) {
        message.error(messages('request.key508')/*请输入用车次数*/);
        return false;
      }
      if ((instantCarAmount === null || instantCarAmount === undefined) && !standardEnable
        && didiFieldProperties.carQuick.carStandard.show
        && didiFieldProperties.carQuick.carStandard.required) {
        message.error(messages('request.key507')/*请输入用车金额*/);
        return false;
      }
    }
    if (nowTab === 'pickup') {
      if (selectCities.length === 0) {
        message.error(messages('request.key505')/*请选择用车城市*/);
        return false;
      }
      if (!pickupPlanList[0].plan) {
        message.error(messages('request.key596')/*请选择接送类型*/);
        return false;
      }
      if (pickupPlanList[0].startDate && pickupPlanList[0].endDate && moment(pickupPlanList[0].startDate).isAfter(pickupPlanList[0].endDate, 'day')) {
        message.error(messages('request.key506')/*结束日期不能早于开始日期*/);
        return false;
      }
    }
    return true;
  };

  //处理数据
  getProcessValue = (values) => {
    const { nowTab, itineraryDetailList, selectRule, selectCities, useCarAmount, useCarNum, editData, startDate, endDate,
      instantCarAmount, instantCarNum, pickupPlanList
    } = this.state;
    let submitData = {};
    if (editData) {
      submitData = JSON.parse(JSON.stringify(editData));
    }
    if (['travel', 'date', 'count'].indexOf(nowTab) > -1) {
      submitData.regulationId = selectRule.regulationId;
      submitData.regulationName = selectRule.regulationName;
    }
    submitData.remark = values['remark'];
    if (nowTab === 'travel') {
      submitData.approvalType = 1;
      submitData.startDate = moment(itineraryDetailList[0].date).utc().format();
      submitData.departureCity = itineraryDetailList[0].cityName;
      submitData.departureCityCode = itineraryDetailList[0].cityCode;
      submitData.endDate = moment(itineraryDetailList[itineraryDetailList.length - 1].date).utc().format();
      submitData.destinationCity = itineraryDetailList[itineraryDetailList.length - 1].cityName;
      submitData.destinationCityCode = itineraryDetailList[itineraryDetailList.length - 1].cityCode;
      let trips = [];
      itineraryDetailList.map((itinerary, index) => {
        if (index !== 0 && index !== itineraryDetailList.length - 1) {
          trips.push({
            endDate: moment(itinerary.date).utc().format(),
            destinationCity: itinerary.cityName,
            destinationCityId: itinerary.cityCode
          });
        }
      });
      submitData.trips = JSON.stringify(trips);
    }
    if (nowTab === 'date') {
      submitData.approvalType = 3;
      submitData.startDate = moment(startDate).second(0).utc().format();
      submitData.endDate = moment(endDate).second(0).utc().format();
      submitData.tripAmount = useCarAmount;
      let trips = [];
      selectCities.map((city, index) => {
        trips.push({
          destinationCity: city.label,
          destinationCityId: city.key
        });
      });
      //兼容新app，新app如果没有城市时要塞一个空的
      if (selectCities.length === 0) {
        trips.push({
          destinationCity: null,
          destinationCityId: null
        });
      }
      submitData.trips = JSON.stringify(trips);
    }
    if (nowTab === 'count') {
      submitData.approvalType = 2;
      submitData.tripTimes = useCarNum;
      let startDateStr = moment(values['tripSDate']).format('YYYY-MM-DD') + ' ' + moment(values['tripSTime']).format('HH:mm');
      submitData.startDate = moment(startDateStr).utc().format();
      let endDateStr = moment(values['tripEDate']).format('YYYY-MM-DD') + ' ' + moment(values['tripETime']).format('HH:mm');
      submitData.endDate = moment(endDateStr).utc().format();
    }
    if (nowTab === 'instant') {
      submitData.approvalType = 4;
      submitData.travelCarItineraryTrips = [];
      selectCities.map((city, index) => {
        submitData.travelCarItineraryTrips.push({
          departureCity: city.label,
          departureCityId: city.key
        });
      });
      submitData.startDate = values['instantSDate'] ? moment(values['instantSDate']).utc().format() : null;
      submitData.endDate = values['instantEDate'] ? moment(values['instantEDate']).utc().format() : null;
      submitData.tripTimes = instantCarNum;
      submitData.tripAmount = instantCarAmount;
    }
    if (nowTab === 'pickup') {
      submitData.approvalType = 5;
      submitData.travelCarItineraryTrips = [];
      selectCities.map((city, index) => {
        submitData.travelCarItineraryTrips.push({
          departureCity: city.label,
          departureCityId: city.key
        });
      });
      submitData.carPickUpType = pickupPlanList[0].plan;
      submitData.startDate = pickupPlanList[0].startDate ? moment(pickupPlanList[0].startDate).utc().format() : null;
      submitData.endDate = pickupPlanList[0].endDate ? moment(pickupPlanList[0].endDate).utc().format() : null;
    }
    return submitData;
  };

  toSubmit = (e) => {
    const { nowTab, selectCities } = this.state;
    const { oid } = this.props.params;
    //validateFieldsAndScroll这个异步执行的，分开校验
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (this.validateData(values)) {
          let submitData = this.getProcessValue(values);
          this.setState({isLoading: true});
          this.handleSubmit(submitData);
        }
      }
    });
  };

  handleSubmit = (submitData) => {
    const { oid } = this.props.params;
    if (!submitData.itineraryOID) {
      travelService.travelDiDiSubmit(oid, [submitData]).then(res => {
        this.setState({isLoading:false});
        message.success(messages('request.key189'/*已保存*/));
        this.closeDiDiSlide();
      }).catch(err=>{
        this.setState({isLoading:false});
        message.error(err.response.data.message);
      });
    } else {
      travelService.travelDiDiUpdate(submitData).then(res => {
        this.setState({isLoading:false});
        message.success(messages('request.key189'/*已保存*/));
        this.closeDiDiSlide();
      }).catch(err=>{
        this.setState({isLoading:false});
        message.error(err.response.data.message);
      });
    }
  };

  renderDidiRules = () => {
    const { nowTab, didiRules } = this.state;
    if (nowTab === 'travel') {
      return didiRules['businessRegulationList'] ? didiRules['businessRegulationList'] : [];
    }
    if (nowTab === 'date') {
      return didiRules['dateRegulationList'] ? didiRules['dateRegulationList'] : [];
    }
    if (nowTab === 'count') {
      return didiRules['numberRegulationList'] ? didiRules['numberRegulationList'] : [];
    }
    return [];
  };

  render() {
    const {
      nowTab, isLoading, itineraryDetailList, baseStartDate, baseEndDate, selectCities, useCarAmount,
      useCarNum, didiRules, selectRule, selectRuleName, startDate, endDate, instantCarNum, instantCarAmount,
      pickupPlanList, typeList, didiFieldProperties, standardEnable, promptList
    } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 18}
    };
    const subFormItemLayout = {
      labelCol: {span: 10},
      wrapperCol: {span: 14}
    };
    const subFormItemLayout2 = {
      labelCol: {span: 0},
      wrapperCol: {span: 24}
    };
    let currentRules = this.renderDidiRules();
    return (
      <div>
        <TravelPrompt promptList={promptList} type={1008} />
        <Tabs onChange={this.onChangeTabs} activeKey={nowTab}>
          {this.renderTabs()}
        </Tabs>
        <div className="travel-didi">
          <Spin spinning={isLoading}>
            <Form>
              {['travel', 'date', 'count'].indexOf(nowTab) > -1 && (
                <div>
                  <Row style={{marginBottom: 10}}>
                    <Col span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
                      <span className="span-required">*</span>{messages('request.key484')/*用车制度*/}：
                    </Col>
                    <Col span={18}>
                      <Select
                        showSearch
                        placeholder={messages('common.please.select')}
                        defaultActiveFirstOption={false}
                        showArrow={true}
                        value={selectRuleName ? selectRuleName : undefined}
                        onSelect={(e, opt) => this.selectRule(e, opt)}
                        optionFilterProp="children"
                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                        getPopupContainer={triggerNode => triggerNode.parentNode}>
                        { currentRules.map((rule) => {
                          return (
                            <Option data-rule={rule} key={rule.regulationId}>
                              {rule.regulationName}
                            </Option>
                          );
                        })}
                      </Select>
                    </Col>
                  </Row>
                  {selectRule && selectRule.showValue && (
                    <Row style={{marginBottom: 10}}>
                      <Col offset={4} span={18} className='show-value-font'>{selectRule.showValue}</Col>
                    </Row>
                  )}
                  <Divider style={{marginTop: 16}}/>
                </div>
              )}
              {nowTab === 'travel' && (
                <div>
                  <Row style={{marginBottom: 10}}>
                    <Col span={4} style={{textAlign: 'right', color: '#000000'}}>{messages('request.key509')/*行程详情*/}：</Col>
                  </Row>
                  {itineraryDetailList.map((subItinerary, index) => {
                    return (
                      <div key={index}>
                        <Row style={{marginBottom: 10}}>
                          <Col offset={1} span={10}>
                            <Row>
                              <Col span={10} style={{lineHeight: '32px', textAlign: 'right'}}>
                                <span className="span-required">*</span>{this.renderLabel(index, 'city')}：
                              </Col>
                              <Col span={14}>
                                <TravelLocation value={itineraryDetailList[index].showValue}
                                                intEnable={true}
                                                vendorType="didi"
                                                isEntity={false}
                                                onSelect={(city) => this.selectCity(city, index)}
                                                isOldDataType={true}/>
                              </Col>
                            </Row>
                          </Col>
                          <Col offset={1} span={10}>
                            <Row>
                              <Col span={10} style={{lineHeight: '32px', textAlign: 'right'}}>
                                <span className="span-required">*</span>{this.renderLabel(index, 'date')}：
                              </Col>
                              <Col span={14}>
                                <DatePicker onChange={(value)=> this.onChangeDate(value, index)}
                                            placeholder={messages('common.please.select')}
                                            disabledDate={this.disabledDate}
                                            allowClear
                                            value={itineraryDetailList[index].date}/>
                              </Col>
                            </Row>
                          </Col>
                          {index !== 0 && index !== 1 && index !== itineraryDetailList.length - 1 && (
                            <Col span={2} style={{lineHeight: '32px', textAlign: 'center'}}>
                              <Icon onClick={() => this.removeSubItinerary(index)} type="close-circle-o" style={{ color: '#FF0000', fontSize: 20, cursor: 'pointer'}}/>
                            </Col>
                          )}
                        </Row>
                        {index + 1 === itineraryDetailList.length - 1 && (
                          <Row style={{margin: '5px 0 10px 0'}}>
                            <Col offset={1} span={10}>
                              <Row>
                                <Col offset={10} span={14}>
                                <span className='default-color-font' style={{cursor: 'pointer'}} onClick={this.addSubItinerary}>
                                  <Icon type="plus-circle"/>&nbsp;{messages('request.key510')/*添加目的城市*/}
                                </span>
                                </Col>
                              </Row>
                            </Col>
                          </Row>
                        )}
                        {(index === 0 || index + 1 === itineraryDetailList.length - 1) && (
                          <Row><Col offset={1} span={21}><Divider dashed /></Col></Row>
                        )}
                      </div>
                    )
                  })}
                </div>
              )}
              {nowTab === 'date' && (
                <div>
                  <Row style={{marginBottom: 10}}>
                    <Col span={4} style={{textAlign: 'right', color: '#000000'}}>{messages('request.key511')/*用车详情*/}：</Col>
                  </Row>
                  <Row style={{marginBottom: 10}}>
                    <Col offset={1} span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
                      <span className="span-required">*</span>{messages('request.key401')/*开始日期*/}：
                    </Col>
                    <Col span={6}>
                      <DatePicker placeholder={messages('common.please.select')}
                                  onChange={(value)=> this.handleChangeDate(value, 'startDate')}
                                  disabledDate={this.disabledDate}
                                  value={startDate}
                                  allowClear/>
                    </Col>
                    <Col offset={1} span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
                      <span className="span-required">*</span>{messages('request.key402')/*结束日期*/}：
                    </Col>
                    <Col span={6}>
                      <DatePicker placeholder={messages('common.please.select')}
                                  onChange={(value)=> this.handleChangeDate(value, 'endDate')}
                                  disabledDate={this.disabledDate}
                                  value={endDate}
                                  allowClear/>
                    </Col>
                  </Row>
                  {didiFieldProperties.businessTripByDate.departureCity.show && (
                    <Row style={{marginBottom: 10}}>
                      <Col offset={1} span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
                        {didiFieldProperties.businessTripByDate.departureCity.required && <span className="span-required">*</span>}
                        {messages('request.key491')/*用车城市*/}：
                      </Col>
                      <Col span={6}>
                        <TravelLocation
                          value={selectCities.length ? selectCities[0].label : undefined}
                          intEnable={true}
                          vendorType="didi"
                          isEntity={false}
                          onSelect={this.handleSelectSingleCity}
                          isOldDataType={true}
                        />
                      </Col>
                    </Row>
                  )}
                  {!standardEnable && didiFieldProperties.businessTripByDate.carStandard.show && (
                    <Row>
                      <Col offset={1} span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
                        {didiFieldProperties.businessTripByDate.carStandard.required && <span className="span-required">*</span>}
                        {messages('request.key489')/*用车金额*/}：
                      </Col>
                      <Col span={3} style={{marginRight: 5}}><Input value='CNY' disabled={true}/></Col>
                      <Col span={3}>
                        <InputNumber placeholder={messages('common.please.input')}
                                     value={useCarAmount}
                                     onChange={num => this.handleChangeCarAmount(num, 'useCarAmount')}
                                     precision={2}
                                     style={{width: '100%'}}
                                     min={0}/>
                      </Col>
                    </Row>
                  )}
                </div>
              )}
              {nowTab === 'count' && (
                <div>
                  <Row style={{marginBottom: 10}}>
                    <Col span={4} style={{textAlign: 'right', color: '#000000'}}>{messages('request.key511')/*用车详情*/}：</Col>
                  </Row>
                  <Row>
                    <Col offset={1} span={10}>
                      <FormItem {...subFormItemLayout} label={messages('request.key291')/*起始日期*/}>
                        {getFieldDecorator('tripSDate', {
                          rules: [
                            {
                              required: true,
                              message: messages('common.please.select')/*请选择*/
                            }
                          ],
                          initialValue: baseStartDate
                        })(
                          <DatePicker placeholder={messages('common.please.select')}
                                      disabledDate={this.disabledDate}
                                      allowClear/>
                        )}
                      </FormItem>
                    </Col>
                    <Col offset={1} span={10}>
                      <FormItem {...subFormItemLayout} label={messages('request.key512')/*起始时段*/}>
                        {getFieldDecorator('tripSTime', {
                          rules: [
                            {
                              required: true,
                              message: messages('common.please.select')/*请选择*/
                            }
                          ],
                          initialValue: moment('00:00', 'HH:mm')
                        })(
                          <TimePicker allowEmpty={false} format='HH:mm' />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col offset={1} span={10}>
                      <FormItem {...subFormItemLayout} label={messages('request.key513')/*截止日期*/}>
                        {getFieldDecorator('tripEDate', {
                          rules: [
                            {
                              required: true,
                              message: messages('common.please.select')/*请选择*/
                            }
                          ],
                          initialValue: baseEndDate
                        })(
                          <DatePicker placeholder={messages('common.please.select')}
                                      disabledDate={this.disabledDate}
                                      allowClear/>
                        )}
                      </FormItem>
                    </Col>
                    <Col offset={1} span={10}>
                      <FormItem {...subFormItemLayout} label={messages('request.key514')/*截止时段*/}>
                        {getFieldDecorator('tripETime', {
                          rules: [
                            {
                              required: true,
                              message: messages('common.please.select')/*请选择*/
                            }
                          ],
                          initialValue: moment('23:59', 'HH:mm')
                        })(
                          <TimePicker allowEmpty={false} format='HH:mm' />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row style={{marginBottom: 10}}>
                    <Col offset={1} span={10}>
                      <Row>
                        <Col span={10} style={{lineHeight: '32px', textAlign: 'right'}}>
                          <span className="span-required">*</span>{messages('request.key487')/*用车次数*/}：
                        </Col>
                        <Col span={14}>
                          <InputNumber placeholder={messages('common.please.input')}
                                       value={useCarNum}
                                       onChange={num => this.handleChangeCarNum(num, 'useCarNum')}
                                       precision={0}
                                       style={{width: '100%'}}
                                       min={1}
                                       max={99}/>
                        </Col>
                      </Row>
                    </Col>
                  </Row>
                </div>
              )}
              {nowTab === 'instant' && (
                <div>
                  <Row style={{marginBottom: 10}}>
                    <Col span={4} style={{textAlign: 'right', color: '#000000'}}>{messages('request.key509')/*行程详情*/}：</Col>
                  </Row>
                  {didiFieldProperties.carQuick.departureCity.show && (
                    <Row style={{marginBottom: 10}} gutter={8}>
                      <Col offset={1} span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
                        {didiFieldProperties.carQuick.carStandard.required && <span className="span-required">*</span>}
                        {messages('request.key491')/*用车城市*/}：
                      </Col>
                      <Col span={7}>
                        <TravelLocation
                          value={selectCities.length ? selectCities[0].label : undefined}
                          intEnable={true}
                          vendorType="ctrip_car"
                          isEntity={false}
                          onSelect={this.handleSelectSingleCity}
                          isOldDataType={true}
                        />
                      </Col>
                    </Row>
                  )}
                  <Row gutter={8}>
                    <Col offset={1} span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
                      <span className="span-required">*</span>{messages('request.key597')/*用车日期*/}：
                    </Col>
                    <Col span={7} className="date-item">
                      <FormItem {...subFormItemLayout2}>
                        {getFieldDecorator('instantSDate', {
                          initialValue: baseStartDate
                        })(
                          <DatePicker placeholder={messages('common.please.select')}
                                      disabledDate={this.disabledDate}
                                      allowClear/>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={2} style={{lineHeight: '32px', textAlign: 'center'}}>--</Col>
                    <Col span={7} className="date-item">
                      <FormItem {...subFormItemLayout2}>
                        {getFieldDecorator('instantEDate', {
                          initialValue: baseEndDate
                        })(
                          <DatePicker placeholder={messages('common.please.select')}
                                      disabledDate={this.disabledDate}
                                      allowClear/>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  {didiFieldProperties.carQuick.useTimes.show && (
                    <Row style={{marginBottom: 10}} gutter={8}>
                      <Col offset={1} span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
                        {didiFieldProperties.carQuick.useTimes.required && <span className="span-required">*</span>}
                        {messages('request.key487')/*用车次数*/}：
                      </Col>
                      <Col span={7}>
                        <InputNumber placeholder={messages('common.please.input')}
                                     value={instantCarNum}
                                     onChange={num => this.handleChangeCarNum(num, 'instantCarNum')}
                                     precision={0}
                                     style={{width: '100%'}}
                                     min={1}
                                     max={99}/>
                      </Col>
                    </Row>
                  )}
                  {!standardEnable && didiFieldProperties.carQuick.carStandard.show && (
                    <Row gutter={8}>
                      <Col offset={1} span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
                        {didiFieldProperties.carQuick.carStandard.required && <span className="span-required">*</span>}
                        {messages('request.key489')/*用车金额*/}：
                      </Col>
                      <Col span={3}><Input value='CNY' disabled={true}/></Col>
                      <Col span={4}>
                        <InputNumber placeholder={messages('common.please.input')}
                                     value={instantCarAmount}
                                     onChange={num => this.handleChangeCarAmount(num, 'instantCarAmount')}
                                     precision={2}
                                     style={{width: '100%'}}
                                     max={9999999999}
                                     min={0}/>
                      </Col>
                    </Row>
                  )}
                </div>
              )}
              {nowTab === 'pickup' && (
                <div>
                  <Row style={{marginBottom: 10}}>
                    <Col span={4} style={{textAlign: 'right', color: '#000000'}}>{messages('request.key509')/*行程详情*/}：</Col>
                  </Row>
                  <Row style={{marginBottom: 10}} gutter={8}>
                    <Col offset={1} span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
                      <span className="span-required">*</span>{messages('request.key491')/*用车城市*/}：
                    </Col>
                    <Col span={7}>
                      <TravelLocation
                        value={selectCities.length ? selectCities[0].label : undefined}
                        intEnable={true}
                        vendorType="ctrip_carpickup"
                        isEntity={false}
                        onSelect={this.handleSelectSingleCity}
                        isOldDataType={true}
                      />
                    </Col>
                  </Row>
                  <Row style={{marginBottom: 10}} gutter={8}>
                    <Col offset={1} span={4} style={{lineHeight: '32px', textAlign: 'right'}}>
                      <span className="span-required">*</span>{messages('request.key593')/*接送类型*/}：
                    </Col>
                    <Col span={7}>
                      <Select allowClear
                              placeholder={messages('common.please.select')/*请选择*/}
                              filterOption={false}
                              value={pickupPlanList[0].plan ? pickupPlanList[0].plan : undefined}
                              onChange={(value) => this.handleSelectType(value, 0)}
                              getPopupContainer={triggerNode => triggerNode.parentNode}>
                        {typeList.map(type => <Option value={type.code} key={type.code}>{type.name}</Option>)}
                      </Select>
                    </Col>
                  </Row>
                  <Row gutter={8} style={{marginBottom: 10}}>
                    <Col offset={1} span={4} style={{lineHeight: '32px', textAlign: 'right'}}> {messages('request.key598')/*有效日期*/}：
                    </Col>
                    <Col span={7} className="date-item">
                      <DatePicker onChange={(value)=> this.onChangePickupDate(value, 0, 'startDate')}
                                  placeholder={messages('common.please.select')}
                                  disabledDate={this.disabledDate}
                                  allowClear
                                  value={pickupPlanList[0].startDate}/>
                    </Col>
                    <Col span={2} style={{lineHeight: '32px', textAlign: 'center'}}>--</Col>
                    <Col span={7} className="date-item">
                      <DatePicker onChange={(value)=> this.onChangePickupDate(value, 0, 'endDate')}
                                  placeholder={messages('common.please.select')}
                                  disabledDate={this.disabledDate}
                                  allowClear
                                  value={pickupPlanList[0].endDate}/>
                    </Col>
                  </Row>
                </div>
              )}
              <Divider style={{marginTop: 10}}/>
              <FormItem {...formItemLayout} label={messages('common.comment'/*备注*/)}>
                {getFieldDecorator('remark', {
                  rules: [{
                    required: didiFieldProperties.remark && didiFieldProperties.remark.required,
                    message: messages('request.key472', {arg1: messages('common.comment'/*备注*/)})
                  }]
                })(
                  <TextArea maxLength="200" rows={4} placeholder={messages('common.please.input'/*请输入*/)} style={{resize: 'none'}}></TextArea>
                )}
              </FormItem>
            </Form>
          </Spin>
        </div>
        <Affix className="travel-affix" offsetBottom={0}>
          <Button type="primary" loading={isLoading} onClick={this.toSubmit}>{messages('request.key211'/*确定*/)}</Button>
          <Button className="travel-type-btn" onClick={this.closeDiDiSlide}>{messages('request.key175'/*取消*/)}</Button>
        </Affix>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    language: state.main.language,
    applicant: state.login.user
  };
}

const wrappedTravelDiDi = Form.create()(TravelDiDi);

export default connect(mapStateToProps)(wrappedTravelDiDi);
